const dbConfig = require('../dbConfig')
const mysql = require('mysql')

let addInfo = (sql, data) => {
    return new Promise((resolve, reject) => {
        try {
            let connection = mysql.createConnection(dbConfig)
            connection.connect()
            connection.query(sql, data, (err) => {
                connection.end()
                if (err) {
                    console.log('[SELECT ERROR]：', err.message)
                    reject({ 'errCode': '400', 'errMsg': 'fail' })
                }
                let obj = { 'errCode': '0', 'errMsg': 'success' }
                resolve(obj)
            })

        } catch (e) {
            console.log(new Date() + 'getStdInfo出错,错误信息:' + e)
            reject({ 'errCode': '400', 'errMsg': 'fail' })
        }
    })
}

let sendRes = (req, res, data) => {
    res.send(data)
}

let AddInfo = {
    addStudent: async (req, res) => {
        let sql = `INSERT INTO student SET ?`
        let obj = await addInfo(sql, req.body)
        sendRes(req, res, obj)
    },
    addCourse: async (req, res) => {
        let sql = `INSERT INTO course SET ?`
        let obj = await addInfo(sql, req.body)
        console.log(obj);
        sendRes(req, res, obj)
    },
    addSC: async (req, res) => {
        let sql = `INSERT INTO SC SET ?`
        let obj = await addInfo(sql, req.body)
        console.log(obj);
        sendRes(req, res, obj)
    }
}

module.exports = AddInfo